import React, {useEffect, useState} from 'react';
import {Avatar, Button, Col, Divider, Rate, Row, Spin, Table} from 'antd';
import axios from 'axios';
import "./css/Reservation.css"
import {useSelector} from "react-redux";
import ReservationDialog from "../components/ReservationDialog";
import {Content} from "../utils/Content";

const Reservation = () => {
    const [services, setServices] = useState([]);
    const [users, setUsers] = useState([]);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    const [reviews, setReviews] = useState({});
    const [currentService, setCurrentService] = useState({});
    const [showReservationDialog, setShowReservationDialog] = useState(false);
    const user = useSelector((state) => state.user.user);

    // 获取服务数据
    const fetchServices = async () => {
        try {
            const _services = await axios.get('http://localhost:5532/service');
            const _users  = await axios.get('http://localhost:5532/user');
            setServices(_services.data.data);
            setUsers(_users.data.data);
        } catch (error) {
            console.error('Error fetching services:', error);
        }
    };

    // 获取用户评价
    const fetchReviews = async (serviceId) => {
        setLoading(true);
        try {
            const response = await axios.get(`http://localhost:5532/review/getByServiceId?serviceId=${serviceId}`);
            setReviews((prevReviews) => ({
                ...prevReviews,
                [serviceId]: response.data.data,
            }));
        } catch (error) {
            console.error('Error fetching reviews:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchServices();
    }, []);

    // 处理展开/收起表格项
    const handleRowExpand = (expanded, record) => {
        const newExpandedRowKeys = expanded
            ? [...expandedRowKeys, record.id]
            : expandedRowKeys.filter(id => id !== record.id);
        setExpandedRowKeys(newExpandedRowKeys);

        // 当展开时，获取该服务的用户评价
        if (expanded && !reviews[record.id]) {
            fetchReviews(record.id);
        }
    };

    // 渲染表格列
    const columns = [
        {
            title: '图片',
            dataIndex: 'img',
            render: img => (
                <img src={'http://localhost:5532/file?name=' + img} alt="service"
                     style={{width: '150px', height: '110px'}}/>
            ),
        },
        {
            title: '服务名称',
            dataIndex: 'name',
        },
        {
            title: '价格',
            dataIndex: 'price',
            render: price => (
                <font style={{color: 'red', fontSize: '20px'}}>¥{price}</font>
            ),
        },
        {
            title: '上架时间',
            dataIndex: 'createdAt',
            render: createdAt => (
                // 长度固定为100px
                <div style={{width: '150px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
                    {createdAt.slice(0, 10)}
                </div>
            ),
        },
        {
            title: '',
            dataIndex: 'id',
            render: (id) => (
                <Button
                    type={'primary'}
                    style={{width: '80px'}}
                    onClick={() => {
                        setCurrentService(services.find(service => service.id === id));
                        setShowReservationDialog(true)
                    }}
                >预约</Button>
            ),
        }
    ];

    // 展开行内容
    const expandedRowRender = (record) => (
        <Row className={'expanded-row'}>
            <Col span={24}>
                <p><strong>服务描述：</strong>{record.description || '暂无描述'}</p>
                <p><strong>服务时长：</strong>{record.duration}分钟</p>
                <div>
                    <strong>用户评价：</strong>
                    {loading ? (
                        <Spin/>
                    ) : (
                        <div>
                            {reviews[record.id] && reviews[record.id].length > 0 ? (
                                reviews[record.id].map((review, index) => (
                                    <Row key={index} className={'review-row'}>
                                        <Col span={24}>
                                            <Avatar src={Content.DEFAULT_AVATAR} />
                                            <span className="username">
                                                {users.find(user => user.id === review.userId).name}
                                            </span>
                                            <p>{review.comment}</p>
                                            <Rate disabled value={review.rating}/>
                                            <Divider plain></Divider>
                                        </Col>
                                    </Row>
                                ))
                            ) : (
                                <p>暂无用户评价</p>
                            )}
                        </div>
                    )}
                </div>
            </Col>
        </Row>
    );

    return (
        <div className={'main-container'}>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={services}
                expandable={{
                    expandedRowRender,
                    expandedRowKeys,
                    onExpand: handleRowExpand,
                }}
                pagination={false}
                sticky={true}
                // scroll={{y: 'calc(100vh - 130px)', x: '100%'}} //占满整个组件
                rowHoverable={false}
            />
            {showReservationDialog &&
                <ReservationDialog
                    user={user}
                    service={currentService}
                    close={() => setShowReservationDialog(false)}
                />
            }
        </div>
    );
};

export default Reservation;
